package com.stone.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.EnumSet;

public enum Singleton {

    INSTANCE;

    /**
     * 因为 @Autowired 只能用在有效 Spring Bean 里面，包括Bean、Service、Component等，而 enum 却不是 Bean，所以 Service 对象不会自动注入进来。
     * 解决办法就是：增加一个内部类，让它在 Spring Boot 启动的时候就往枚举中注入。
     */
    @Autowired
    BusinessService businessService;

    public void businessMethod() {
        System.err.println("I am a businessMethod.");
        businessService.test();
    }

    public void setBusinessService(BusinessService businessService) {
        this.businessService = businessService;
    }

    @Component
    public static class SetPostService {
        // 因为这个类是个 Component，所以 Spring Boot 启动的时候会自动注入依赖
        @Autowired
        private BusinessService businessService;

        @PostConstruct
        public void setPostService() {
            for (Singleton singleton : EnumSet.allOf(Singleton.class)) {
                singleton.setBusinessService(businessService);
            }
        }
    }
}
